<!DOCTYPE html>
<html lang="zh" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>Web Audio API 测试</title>
</head>
<body>
<div>
    <audio controls="controls" >
        <source src="music-stream" type="audio/mpeg">
    </audio>
</div>
<table>
    <tr>
        <td>参数:</td>
        <td><input style="width: 390px;" type="text" name="type" id="type"></td>
        <td>
            <button onclick="onSendMessage()">发送消息</button>
        </td>
        <td>
            <button onclick="onCloseMessage()">断开连接</button>
        </td>
    </tr>

</table>
</body>

<script>
    //Web Audio API
    var context;
    try {
        context = new(window.AudioContext || window.webkitAudioContext)();
    } catch (e) {
        alert('您当前的浏览器不支持Web Audio API ');
    }


    //测试
    var wsServer = 'ws://localhost:8080/audio';

    /**
     WebSocket服务连接
     */
    var objSocket = new WebSocket(wsServer);
    objSocket.onopen = function(evt) {
        onOpen(evt)
    };
    objSocket.onclose = function(evt) {
        onClose(evt)
    };
    objSocket.onmessage = function(evt) {
        onMessage(evt)
    };
    objSocket.onerror = function(evt) {
        onError(evt)
    };

    function onOpen(evt) {
        console.log("Connected to WebSocket server.");
    }

    function onClose(evt) {
        console.log("Disconnected");
    }

    function onError(evt) {
        console.log('Error occured: ' + evt.data);
    }

    function onMessage(evt) { //websocket返回数据信息处理
        console.log('Retrieved data from server: ' + evt.data);

        var reader = new FileReader(); //文件阅读器
        reader.readAsArrayBuffer(evt.data); //读取成ArrayBuffer对象
        reader.onload = function() { //读取完毕
            //解码
            context.decodeAudioData(this.result, function(buffer) {
                playSound(buffer);
            }, function(e) {
                "Error with decoding audio data" + e.err
            });
        }

        //--------onMessage-----end-----------
    }

    //播放声音
    function playSound(buffer) {
        var source = context.createBufferSource(); // 创建一个声音源
        source.buffer = buffer; // 告诉该源播放何物
        source.connect(context.destination); //将该源与硬件相连
        source.start(0); // 开始播放
    }

    //发送消息
    function onSendMessage() {
        var mess = document.getElementById("type").value;
        objSocket.send(mess);
        /* if (window.confirm("发送消息：" + mess)) {
            //alert("确定");
            objSocket.send(mess);
            return true;
        } else {
            //alert("取消");
            return false;
        } */
    }

    //关闭连接
    function onCloseMessage() {
        objSocket.close()
    }
</script>
</html>
